package pri.zxx.webdemo.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.image.BufferedImage;
import java.math.BigDecimal;

/**
 * 图片加水印
 */
@Slf4j
public class ImageMarkUtils {

    /**
     * @param contentWord      水印内容
     * @param markContentColor 水印颜色
     * @param rotate           是否旋转
     */
    public static BufferedImage addWaterMark(MultipartFile file, String contentWord, Color markContentColor, boolean rotate) {

        try {
            // 读取原图片信息
            Image srcImg = ImageIO.read(file.getInputStream());//文件转化为图片
            int srcImgWidth = srcImg.getWidth(null);//获取图片的宽
            int srcImgHeight = srcImg.getHeight(null);//获取图片的高

            BufferedImage image = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            //根据Font取得字符（字符串）的长度，当宽度不够时，y坐标递增
            Graphics2D g2d2 = image.createGraphics();
            g2d2.drawImage(
                    srcImg.getScaledInstance(srcImg.getWidth(null),
                            srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0,
                    null);
            int fontSize = (srcImgWidth / 300) * 5;
            //初始化一下字体
            Font font = new Font("微软雅黑", Font.PLAIN, fontSize);
            g2d2.setFont(font);
            //文字 变化
            //通过比较字符串体每次设定完尺寸后的宽度是否超过图片宽度限定尺寸，从而减小字体尺寸
            while (g2d2.getFontMetrics().stringWidth(contentWord) > srcImgWidth) {
                fontSize = fontSize - 1;
            }
            font = new Font("微软雅黑", Font.PLAIN, fontSize);
            g2d2.setFont(font);
            if (markContentColor == null) {
                markContentColor = new Color(255, 255, 255, 128);
            }
            g2d2.setColor(markContentColor); //根据图片的背景设置水印颜色

            FontRenderContext frc = g2d2.getFontRenderContext();
            Rectangle bounds = font.getStringBounds(contentWord, frc).getBounds();
            int strWidth = bounds.width;
            int strHeight = bounds.height;

            //设置水印的坐标
            if (rotate) {
                int left = (srcImgWidth - strWidth) / 2; //左边位置
//                int top = (srcImgHeight - strHeight) / 2 + metrics.getAscent();
                g2d2.rotate(0.5);
                g2d2.drawString(contentWord, left, 0);  //画出水印
            } else {
                BigDecimal mlt = new BigDecimal("1.01");
                BigDecimal strWid = new BigDecimal(strWidth);
                BigDecimal multiply = strWid.multiply(mlt);
                g2d2.drawString(contentWord, srcImgWidth - multiply.intValue(), (srcImgHeight - strHeight / 2));  //画出水印
            }
            g2d2.dispose();
            return image;
        } catch (Exception e) {
            // TODO: handle exception
            log.error("为图片添加水印失败", e);
            return null;
        }
    }
}
